package com.qiwo.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.qiwo.common.annotation.Log;
import com.qiwo.common.base.AdminBaseController;
import com.qiwo.common.domain.ContentDO;
import com.qiwo.common.domain.Tree;
import com.qiwo.common.service.ContentService;
import com.qiwo.common.type.EnumErrorCode;
import com.qiwo.common.utils.MD5Utils;
import com.qiwo.common.utils.Result;
import com.qiwo.common.utils.ShiroUtils;
/*import com.qiwo.oss.domain.FileDO;
import com.qiwo.oss.service.FileService;*/
import com.qiwo.common.utils.cache.Cache;
import com.qiwo.sys.domain.MenuDO;
import com.qiwo.sys.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <pre>
 * </pre>
 * <small> 2018年3月23日 | Aron</small>
 */
@Controller
@RequestMapping("/main")
public class LoginController extends AdminBaseController {


   /* @Autowired
    FileService fileService;*/

    @GetMapping({ "/", "" })
    @Log("重定向到登录")
    String welcome(Model model) {
        return "redirect:/main/login";
    }

    @Autowired
    MenuService menuService;
    @Log("请求访问主页")
    @GetMapping({ "/index" })
    String index(Model model) {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        model.addAttribute("username", getUser().getUsername());
        //  FileDO fileDO = fileService.selectById(getUser().getPicId());
        model.addAttribute("picUrl", null == null ? "/img/logo-log.png" : "");
        return "index_v1";
    }

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @GetMapping("/authcode")
    String authcode() {
        return "authCode";
    }

    @Autowired
    private ContentService contentService;

    @PostMapping("/AjaxauthCode")
    @ResponseBody
    Result<String> ajaxauthCode(String authCode) {
        try {
           String code=MD5Utils.decodeBase64(authCode);
            JSONObject jsonObject=JSONObject.parseObject(code);
            if(jsonObject.get("urls")!=null){
                ContentDO contentDO=new ContentDO();
                contentDO.setTypeId(0L);
                contentDO.setContent(authCode);
                ContentDO content2 = contentService.findOneByKv("type_id",contentDO.getTypeId());
                if(content2!=null){
                    contentDO.setId(content2.getId());
                    boolean update = contentService.updateById(contentDO);
                    Cache.remove("autoPass");
                    Cache.add("AuthCode",code);
                    return update ? Result.ok() : Result.fail();
                }
                Cache.remove("autoPass");
                contentService.insert(contentDO);
                Cache.add("AuthCode",code);
                return Result.ok();
            }else{
                return Result.build(EnumErrorCode.userLoginFail.getCode(), "授权码有误 ");
            }
        } catch (Exception e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), "授权码有误 ");
        }
   }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    Result<String> ajaxLogin(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return Result.ok();
        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
        }
    }

    @GetMapping("/logout")
    @Log("退出")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/main/login";
    }
    
    @Log("主页")
    @GetMapping("/main")
    String main() {
        return "main";
    }

    @Log("错误403")
    @GetMapping("/403")
    String error403() {
        return "403";
    }

}
